package com.work.servlet;

import com.work.bean.Student;
import com.work.bean.Teacher;
import com.work.service.UserService;
import com.work.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2017/9/29.
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doPost(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserService service = new UserServiceImpl();
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

//        if (req.getParameter("username") != null && req.getParameter("password") == null) {
//
//            int userType = Integer.parseInt(req.getParameter("userType"));
//            System.out.println(userType+"-----");
//            boolean flag = false;
//            if (userType == 0) {
//                flag = service.verifyStuName(req.getParameter("username"));
//            }else if (userType == 1){
//                flag = service.verifyTeacherName(req.getParameter("username"));
//            }
//            System.out.println(flag);
//            if (flag) {
//                resp.getWriter().write("用户已存在");
//            } else {
//                resp.getWriter().write("用户名可用");
//            }
//
//        } else
        if (req.getParameter("username") != null && req.getParameter("password") != null) {

            String username = req.getParameter("username");
            String password = req.getParameter("password");
            int userType = Integer.parseInt(req.getParameter("userType"));

            boolean flag = false;
            if (userType == 0) {
                flag = service.insertStudent(new Student(username, password));
            } else if (userType == 1) {
                flag = service.insertTeacher(new Teacher(username, password));
            }

            if (flag) {
                req.getSession().setAttribute("username", username);
                req.getSession().setAttribute("password", password);
                resp.sendRedirect("login.jsp");
//                resp.getWriter().write("<a href='login.jsp'>注册成功,点我登录</a>");
            } else {

                resp.getWriter().write("注册失败");
            }
        }


    }
}
